<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\wechat\controller;

use suifeng\Controller;
use suifeng\wechat\WechatSDK;

class Callback extends Controller
{
    public function index($mp_number = null)
    {
        if (empty($mp_number) || $mp_number == 'default') {
            $mp_number = service('wechat/mp')->get_default_mp_number();
        }

        $this->wxobj = service('wechat/mp')->get_wx_object($mp_number);

        $this->wxobj->valid();
        $this->wxobj->getRev();

        if ($this->_check_duplicate($this->wxobj)) {
            return;
        }

        $this->log_post_msg();

        $type = $this->wxobj->getRev()->getRevType();
        switch($type) {
            case WechatSDK::MSGTYPE_EVENT:
                $this->_handle_event();
                break;

            case WechatSDK::MSGTYPE_TEXT:
                $this->wxobj->text("hello, I'm wechat")->reply();
                break;
        }
    }

    private function log_post_msg()
    {
        $data['mp_number'] = $this->wxobj->getRevTo();
        $data['msg_id'] = $this->wxobj->getRevID();
        $data['msg_type'] = $this->wxobj->getRevType();
        $data['from_name'] = $this->wxobj->getRevFrom();
        $data['to_name'] = $this->wxobj->getRevTo();
        $data['msg_content'] = $this->wxobj->getRevContent();
        $data['create_time'] = $this->wxobj->getRevCtime();
        $data['update_time'] = $this->wxobj->getRevCtime();
        $data['receive_data'] = helper('admin/json')->encode($this->wxobj->getRevData());
        $data['post_xml'] = file_get_contents("php://input");
        model('wechat/log')->create($data);
    }

    private function _check_duplicate($wxobj)
    {
        $where['from_name'] = $wxobj->getRev()->getRevFrom();
        $where['create_time'] = $wxobj->getRev()->getRevCtime();
        $result = model('wechat/log')->where($where)->find();
        return $result !== null;
    }

    private function _handle_event()
    {
        $event = $this->wxobj->getRevEvent();

        switch($event['event']) {
            case WechatSDK::EVENT_SUBSCRIBE: //关注
                $this->_handle_subscribe();
                break;

            case WechatSDK::EVENT_UNSUBSCRIBE: //取消关注
                $this->_handle_unsubscribe();
                break;

            default:
                $this->wxobj->text('正在完善')->reply();
                break;
        }
    }

    /**
     * 关注事件。
     */
    private function _handle_subscribe()
    {
        $where_map['mp_number'] = array('eq', $this->wxobj->getRevTo());
        $where_map['openid'] = array('eq', $this->wxobj->getRevFrom());
        $user_info = model('wechat/user')->where($where_map)->find();
        if ($user_info === null) {
            $user_info = model('wechat/user')->initDefault();
            $user_info['mp_number'] = $this->wxobj->getRevTo();
            $user_info['openid'] = $this->wxobj->getRevFrom();
            $user_info->save();
        }

        service('wechat/user')->update_user_info($this->wxobj->getRevTo(), $this->wxobj->getRevFrom());

        $this->wxobj->text('关注')->reply();

        // 扫描二维码关注，带了场景值。 场景值以qrscene_为前缀，后面为二维码的参数值
        $event = $this->wxobj->getRevEvent();
        if (isset($event['EventKey'])) {
            //
        }
    }

    /**
     * 取消关注事件。
     * 取消关注后，不要再发送信息给用户，因为它已经收不到了。
     */
    private function _handle_unsubscribe()
    {
        $where_map['mp_number'] = array('eq', $this->wxobj->getRevTo());
        $where_map['openid'] = array('eq', $this->wxobj->getRevFrom());
        $user_info = model('wechat/user')->where($where_map)->find();
        if ($user_info !== null) {
            $user_info['subscribe'] = 0;
            $user_info['subscribe_time'] = 0;
            $user_info->save();
        }
    }
}
